import CryptoJS from 'crypto-js'

const cryptoUtils = {
  async encryptParams(params) {
    const plaintext = JSON.stringify(params)
    console.log(plaintext)
    const encryptionKey = 'G4uasIFz4Gy7trW9'
    
    // 发送请求获取随机数
    const ivStr = await this.getRandomIV()
    const iv = CryptoJS.enc.Hex.parse(ivStr)
    
    const encrypted = CryptoJS.AES.encrypt(
      plaintext,
      CryptoJS.enc.Utf8.parse(encryptionKey),
      {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }
    )

    const ciphertext = encrypted.toString()

    const requestData = {
      ciphertext,
      ivStr
    }
	console.log(JSON.stringify(requestData))
    return JSON.stringify(requestData)
  },
  
  getRandomIV() {
    return new Promise((resolve, reject) => {
      // 在这里发送请求获取随机数
      wx.request({
        url: 'https://thywtjp.lysport.net/index.php/api/common/getRandomIV',
		// url: this.$https.baseUrl + "common/getRandomIV",
        success: (res) => {
          resolve(res.data)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  }
}

export default cryptoUtils